import { HttpService } from '@nestjs/axios';
import { Injectable, Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { mkdir, writeFile } from 'fs/promises';
import * as fs from 'fs';
import { join } from 'path';

@Injectable()
export class FileMangerService {
  constructor(private readonly config: ConfigService) {}

  baseDirPath = () => {
    const path = join(this.config.get('staticPath'), 'files');
    return path;
  };

  getLocalFilePath = (nameKey: string) => {
    const path = join(this.config.get('staticPath'), 'files', nameKey);
    return path;
  };

  getTempDirWithId = async (id: string) => {
    // 根据文件名处理
    const path = join(this.baseDirPath(), `_temp${id}`);
    if (fs.existsSync(path)) {
      return path;
    }
    await mkdir(path);
    return path;
  };

  getFileKey = async (id: string, fileName: string) => {
    const fileKey = `temp${id}${fileName}`;
    // const filePath = join(path, fileName);
    return fileKey;
  };

  getTempPathWithName = async (id: string, fileName: string) => {
    const key = await this.getFileKey(id, fileName);
    const path = join(this.baseDirPath(), key);
    // const filePath = join(path, fileName);
    return path;
  };

  getTempRelativePathWithName = async (id: string, fileName: string) => {
    const path = await this.getTempPathWithName(id, fileName);
    const pathLast = path.split('static')?.pop();
    const filterPath = 'static' + pathLast;
    // const filePath = join(path, fileName);
    Logger.log(filterPath, 'getTempRelativePathWithName');
    return filterPath;
  };

  clearTempDirFiles = async () => {
    const directoryPath = join(this.config.get('staticPath'), 'files'); // 指定要清理的目录路径
    const files = await fs.promises.readdir(directoryPath);

    for (const file of files) {
      const filePath = `${directoryPath}/${file}`;
      const fileStat = await fs.promises.stat(filePath);
      // 计算文件的时间差是否大于 1 小时 (1 * 60 * 60 * 1000 毫秒)
      const timeDifference = Date.now() - fileStat.mtime.getTime();
      if (timeDifference > 1 * 60 * 60 * 1000 ) {
        await fs.promises.unlink(filePath);
        Logger.log('缓存文件已清理')
      }
    }
  };
}
